//
// Created by hsj on 2022/3/3.
//

#include "t_dynamic_cast.h"
namespace dynamic_cast_test{

    void test(){
        Grand *pg;
        SuperB *ps;
        for (int i = 0; i < 5; ++i) {
            cout<<"--------------------------------------"<<endl;
            pg = getOne();
            pg->speak();
            //如果是引用，没有空引用对应，此时使用异常捕获机制
            //多态时候使用
            if (ps = dynamic_cast<SuperB *>(pg)){
                (*ps).say();
            }
            //类似java的instanceOf
            if (typeid(Magnificent) == typeid(*pg)){
                cout<<"OK ,you are really Magnificent."<<endl;
            }
        }
    }

    Grand *getOne(){
        Grand *p = NULL;
        switch (rand() % 3) {
            case 0:
                p = new Grand(rand() % 3);
                break;
            case 1:
                p = new SuperB(rand() % 3);
                break;
            case 2:
                p = new Magnificent(rand() % 3,'A' + rand() % 26);
                break;
        }
        return p;
    }
}